package indexof

var ASCII_SIZE = 128

type Sunday struct {
}

func GetMove(pattern []rune) [] int {

	patternLen := len(pattern)

	move := make([]int, ASCII_SIZE)
	//主串参与匹配最末位字符移动到该位需要移动的位数
	for i := 0; i < ASCII_SIZE; i++ {
		move[i] = patternLen + 1
	}

	for i := 0; i < patternLen; i++ {
		move[pattern[i]] = patternLen - i
	}

	return move
}

func (this Sunday) IndexOf(main, pattern string) int {

	mainRuns, patternRuns := []rune(main), []rune(pattern)

	mainLen, patternLen := len(mainRuns), len(patternRuns)

	move := GetMove(patternRuns)

	s := 0 //模式串头部在字符串位置

	var j int //模式串已经匹配了的长度

	//到达末尾之前
	for s <= mainLen-patternLen {

		j = 0

		for  mainRuns[s+j] == patternRuns[j] {
			j++
			if j >= patternLen {
				return s
			}
		}

		if s+patternLen == mainLen {

			return -1
		}

		s += move[mainRuns[s+patternLen]]
	}
	return -1
}
